<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/5/23
 * Time: 下午1:59
 */

namespace common\jobs;

use common\models\UserCoupon;
use common\models\Product;
use common\models\CouponCategory;
use common\models\User;
use common\service\UserService;
use yii\base\BaseObject;
use yii\queue\Queue;
use yii\queue\RetryableJobInterface;
use yii;

class IssueCouponsJob extends BaseObject implements RetryableJobInterface
{
    public $userid;
    public $goodsid;


    /**
     * @param Queue $queue which pushed and is handling the job
     */
    public function execute($queue)
    {
        try {
                $good = Product::findOne($this->goodsid);
                $couponCategory=CouponCategory::findOne($good->coupon_id);
                $coupon = UserService::createUserCoupon($couponCategory,$this->userid);

                $user=User::findOne($this->userid);
            $dataVariables =  [['Name' => 'CARD_NO', 'Value' => $coupon['code']]];
            Yii::$app->queue_sms->push(new SmsJob([
                'phone' => $user->phone,
                'dataVariables' => $dataVariables,
                'template' => '000015'
            ]));
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * @return int time to reserve in seconds
     */
    public function getTtr()
    {
        return 0;
    }

    /**
     * @param int $attempt number
     * @param \Exception $error from last execute of the job
     * @return bool
     */
    public function canRetry($attempt, $error)
    {
        return $attempt < 3;
    }
}
